#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <wiringPi.h>
#include "server.h"

static void init_dev()
{
    wiringPiSetup();
}

static int makethread(void *(*fn)(void*), void* arg)
{
    int             err;
    pthread_t       tid;
    pthread_attr_t  attr;

    err = pthread_attr_init(&attr);
    if (err != 0)
        return (err);
    err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    if (err == 0)
        err = pthread_create(&tid, &attr, fn, arg);
    pthread_attr_destroy(&attr);
    return  err;
}


static void* thread_fun(void* arg)
{
    int ret = 0;

    for (; ret >= 0;){
        ret = deal_request((int)arg);
    }
}

int main(/*int argc, char* argv[]*/)
{
    int listenfd, err;

    init_dev();
    listenfd = start_server();

    for (;;){
        int connfd = wait_for_connection(listenfd);
        printf("connected from %d.\n", connfd);
        err =  makethread(thread_fun, (void*)connfd);
        if (err)
            fprintf(stdout, "start thread for client connection. \n");
    }
}

